package com.yanfan.modbus.frame.abs;


import com.yanfan.common.ByteUtil;
import com.yanfan.modbus.exception.ModbusTransportException;
import io.netty.buffer.ByteBuf;


abstract public class ReadResponse extends ModbusResponse {
    private byte[] data;

    public ReadResponse(int slaveId) throws ModbusTransportException {
        super(slaveId);
    }

    public ReadResponse(int slaveId, byte[] data) throws ModbusTransportException {
        super(slaveId);
        this.data = data;
    }


    @Override
    protected void readResponse(ByteBuf buf) {
        int numberOfBytes = buf.readUnsignedByte();
        if (buf.readableBytes() < numberOfBytes) {
            throw new ArrayIndexOutOfBoundsException();
        }
        data = new byte[numberOfBytes];
        buf.readBytes(data);
    }


    @Override
    protected void writeResponse(ByteBuf queue) {
        queue.writeByte(data.length);
        queue.writeBytes(data);
    }


    public byte[] getData() {
        return data;
    }


    public short[] getShortData() {
        return ByteUtil.convertToShorts(data);
    }


    public boolean[] getBooleanData() {
        return ByteUtil.convertToBooleans(data);
    }


    public String toString(boolean numeric) {
        if (data == null) {
            return " [null]";
        }
        return "len=" + (numeric ? data.length / 2 : data.length * 8) + ", " + ByteUtil.dumpHex(data);
    }
}
